package com.cn.ccp.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cn.ccp.action.course.CourseOutlineAction;
import com.cn.ccp.bean.FilePathBean;
import com.cn.ccp.service.course.FilePathService;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Contants;
import com.cn.ccp.util.Converter;

@SuppressWarnings("serial")
public class UploadCourseOutline extends HttpServlet {
	private Logger log = Logger.getLogger(UploadCourseOutline.class);
	public UploadCourseOutline(){
		
	}
	
	
	public FilePathBean getFilePaht(){
		ServletContext servletContext = this.getServletContext();  
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
        return ((FilePathService) ctx.getBean("filePathService")).getFlagBean(); 
	}
	

	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String uid = request.getParameter("uid");
		String courseId = request.getParameter("courseId");
		String typeName = request.getParameter("type");
		log.info("------------typeName = "+typeName);
		String derectory = null;
		if(typeName.equalsIgnoreCase(Contants.OUTLINE_DERECT))
			derectory = Contants.OUTLINE_DERECT;
		else
			derectory = Contants.EVALUATION_DERECT;
		String savePath = CCPContants.SYS_PATH+"files"+File.separator+ uid + File.separator + courseId + File.separator + derectory + File.separator;
		FilePathBean filePathBean = getFilePaht();
		if(filePathBean != null){
			savePath = filePathBean.getPath()+uid+ File.separator + courseId + File.separator + derectory + File.separator;
		}
		log.info(savePath);
		File f1 = new File(savePath);
		if (!f1.exists()) {
			f1.mkdirs();
		} 
		File[] ff = f1.listFiles();
		for(File f : ff){
			f.delete();
		}
		
		DiskFileItemFactory fac = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");
		List fileList = null;
		try {
			fileList = upload.parseRequest(request);
		} catch (FileUploadException ex) {
			return;
		}
		Iterator<FileItem> it = fileList.iterator();
		String name = "";
		String sourseName = "";
		String extName = "";
		 
		while (it.hasNext()) {
			FileItem item = it.next();
			if (!item.isFormField()) {
				name = item.getName();
				sourseName = name ;
				long size = item.getSize();
				String type = item.getContentType();
				System.out.println(size + " " + type);
				if (name == null || name.trim().equals("")) {
					continue;
				}
				//扩展名格式：  
				if (name.lastIndexOf(".") >= 0) {
					extName = name.substring(name.lastIndexOf("."));
				}
				File file = null;
				do {
					//生成文件名：
					name = UUID.randomUUID().toString();
					file = new File(savePath + name + extName);
				} while (file.exists());
				File saveFile = new File(savePath + name + extName);
				try {
					item.write(saveFile);
					/**
					 * 对上传的文件进行处理
					 * 1、视频文件不做处理
					 * 2、swf文件不做处理
					 * 3、pdf文件只做到swf转换处理
					 * 4、其他文字文件处理流程：源文件-》pdf文件-》swf文件。
					 */
//					File sourceFile = new File(savePath + name + extName);
					File pdfFile = new File(savePath + name + ".pdf");
					File swfFile = new File(savePath + name + ".swf");
					try {
						//判断是否为视频格式
						if(CCPContants.uploadVideoLayout.indexOf(extName.substring(1)) != -1){
							//是视频的话就直接保存，不用进行任何转换
							Converter.encodeFile(saveFile);
							//CCPContants.copyFile(sourceFile, new File(CCPContants.SYS_PATH + File.separator +"video"+File.separator+ CCPContants.getCurrUserId() +File.separator+name + extName));
						}else{
							if(extName.substring(1).equalsIgnoreCase("swf")){
								Converter.encodeFile(saveFile);
//								CCPContants.copyFile(saveFile, swfFile);
							}else if(extName.substring(1).equalsIgnoreCase("pdf")){
								Converter.encodeFile(saveFile);
								//直接转换成swf文件
//								Converter.convertPDF2SWF(pdfFile.getPath(), swfFile.getParent(), swfFile.getName());
//								extName = ".swf";
//								saveFile.delete();
//								pdfFile.delete();
							}else{
								//需要先进行pdf转换，再进行swf转换
								pdfFile = Converter.convertTo(saveFile,"pdf");
								Converter.encodeFile(pdfFile);
//								Converter.convertPDF2SWF(pdfFile.getPath(), swfFile.getParent(), swfFile.getName());
								extName = ".pdf";
								saveFile.delete();
//								pdfFile.delete();
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
//						sourceFile.delete();
						pdfFile.delete();
						swfFile.delete();
						response.getWriter().print(name + extName);
						return ;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
//		response.getWriter().print("files"+File.separator+ uid + File.separator + extName);
		response.getWriter().print(name + extName);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
}
